#include <stdio.h>
#include <assert.h>

int factorial(int N);

int factorial2(int N);

/**
 * File: factorial.c
 * ----------------------
 * 如何计算一个数的阶乘？
 * N!=N*(N-1)!
 * 
 * 
 */
int main(int argc, char **argv){
    // Testing factorial
    // printf("Testing factorial(0)...\n");
    // assert(factorial(0) == 1);
    // printf("Factorial(0) test passed.\n");

    // printf("Testing factorial(1)...\n");
    // assert(factorial(1) == 1);
    // printf("Factorial(1) test passed.\n");

    // printf("Testing factorial(2)...\n");
    // assert(factorial(2) == 2);
    // printf("Factorial(2) test passed.\n");


    // printf("Testing factorial(3)...\n");
    // assert(factorial(3) == 6);
    // printf("Factorial(3) test passed.\n");

    // printf("Testing factorial(4)...\n");
    // assert(factorial(4) == 24);
    // printf("Factorial(4) test passed.\n");


    // Testing factorial2
    printf("Testing factorial2(0)...\n");
    assert(factorial2(0) == 1);
    printf("Factorial2(0) test passed.\n");

    printf("Testing factorial2(1)...\n");
    assert(factorial2(1) == 1);
    printf("Factorial2(1) test passed.\n");

    printf("Testing factorial2(2)...\n");
    assert(factorial2(2) == 2);
    printf("Factorial2(2) test passed.\n");


    printf("Testing factorial2(3)...\n");
    assert(factorial2(3) == 6);
    printf("Factorial2(3) test passed.\n");

    printf("Testing factorial2(4)...\n");
    assert(factorial2(4) == 24);
    printf("Factorial2(4) test passed.\n");

    return 0;
}

/**
 * Program 5.1 Factorial function (recursive implementation)
 * This recursive function computes the function N!, using the standard recursive definition.
 * It returns the correct value when called with N nonnegative and sufficiently small that N! can be represented as an int.
 */
int factorial(int N){
    if (N <= 1) {
        return 1;
    }else {
        return N * factorial(N-1);
    }
}

/**
 * 计算N!的迭代版本
 */
int factorial2(int N){
    int t = 1;
    int i;
    for (i=1; i<=N; i++) {
        t *= i;
    }
    return t;
}

